<?php
namespace app\common\netfilter;

use app\common\service;
class Rule 
{
    private $osRule;
    private $ip;
    function __construct($host_id)
    {
        $HostLearnConfig = new service\HostLearnConfig();
        $config = $HostLearnConfig->findOne($host_id);
        $HostContact = new service\HostContact();
        $this->ip = $HostContact->findIpByHostId($host_id);
        $this->change($config['use_rule']);
    }

    /**
     * @name: 选择 规则内容
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-11-12 15:57:31
     */
    function change ($useRule)
    {
        switch ($useRule) {
            case 2 :
                $this->osRule = new Windows2003Rule();
                break;
            case 3 :
                $this->osRule = new Windows2008Rule();
                break;
            case 4 :
                $this->osRule = new Windows2012Rule();
                break;
            default :
                $this->osRule = new LinuxRule();
        }
    }

    /**
     * @name:  防火墙规则
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-11-12 16:08:27
     */
    function firewallRule ($data, $batch = false)
    {
        if (empty($data))
        {
            return [];
        }

        $return = [];
        $method = get_class_methods($this->osRule);
        foreach ($data as $v)
        {
            if($batch)
            {
                $v['direction'] == 1 ? $v['src_ip'] = $this->ip : $v['dest_ip'] = $this->ip;
            }
            $src_ip_a = explode(',', $v['src_ip']);
            $dest_ip_a = explode(',', $v['dest_ip']);
            foreach($src_ip_a as $src_ip)
            {
                $v['src_ip'] = $src_ip;
                foreach ($dest_ip_a as $dest_ip)
                {
                    $v['dest_ip'] = $dest_ip;
                    $v['alias'] = 'asmp_' . md5($v['src_ip'] . '-' . $v['src_port'] . '-' . $v['dest_ip'] . '-' . $v['dest_port'] . '-' . $v['protocols']);
                    $return[] = $this->creatRuleStr($method, $v);
                }
            }
        }

        return $return;
    }

    /**
     * @name: 创建规则 字符
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-02 17:47:32
     */
    function creatRuleStr ($method, $ruleData)
    {
        $return = $this->osRule->rulehead;
        foreach ($method as $cv)
        {
            if($cv == 'ip' || $cv == 'port')
            {
                $tmp =  [$ruleData['src_' . $cv],$ruleData['dest_' . $cv]];
            }
            else
            {
                if(isset($ruleData[$cv]))
                {
                    $tmp = [$ruleData[$cv]];
                }
                else
                {
                    $tmp = [];
                }
            } 
            $return .= ' ';
            $return .= call_user_func_array([$this->osRule, $cv], $tmp);
        }
        return $return;
    }
}